package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService{

    @Value("${image.path}")
    private String dirPath;
    @Value("${image.dir}")
    private String dir;

    private static Set<String>  imageSet = new HashSet<>();
  
    static {
        imageSet.add(".jpg");
        imageSet.add(".png");
        imageSet.add(".gif");
    }

    @Override
    public ImageVO upload(MultipartFile uploadFile) {
        //1.校验图片类型是否正确 jpg/png/gif  1.正则表达式  2.准备集合之后进行校验
        String fileName = uploadFile.getOriginalFilename();
        fileName.toLowerCase();          //将所有字符转换为小写
        int index = fileName.lastIndexOf(".");
        String fileType = fileName.substring(index);
        if(!imageSet.contains(fileType)){
            //用户上传的不是图片 返回上传失败
            return ImageVO.fail();
        }

        //2.校验上传的数据是否为恶意程序-----宽度和高度是否为null   利用图片的api
        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            System.out.println(bufferedImage.getPropertyNames());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            System.out.println(height);
            if(width==0 || height==0){
                return ImageVO.fail();
            }

            //3.采用分目录存储的方式
           // String dirPath = "C:/demo";
            //3.1分目录存储目录1  hash方式
            //3.1分目录存储目录1  时间方式存储
            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //3.2  准备文件存储目录
            String imageDir = dirPath+dateDir;
            File imageFile = new File(imageDir);
            if(!imageFile.exists()){
                imageFile.mkdirs();
            }
            //4.实现文件上传
            //4.1  动态拼接文件名称
            String uuid = UUID.randomUUID().toString().replace("-","");
            String realFileName = uuid+fileType;
            File imageFileDir = new File(imageDir+realFileName);
            uploadFile.transferTo(imageFileDir);

            String url =dir+dateDir+realFileName;
            return ImageVO.success(url,width,height);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }


    }
}
